package com.foldingleaf.web;

import com.foldingleaf.collections.service.ISysCollectionService;
import com.foldingleaf.framework.web.service.UserDetailsServiceImpl;
import com.foldingleaf.order.domain.SysCollectionOrder;
import com.foldingleaf.order.service.ISysCollectionOrderService;
import com.foldingleaf.show.domain.SysCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class RedisListener extends KeyExpirationEventMessageListener {
    //logger
    private static final Logger log = LoggerFactory.getLogger(RedisListener.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ISysCollectionOrderService sysCollectionOrderService;
    @Autowired
    private ISysCollectionService sysCollectionService;


    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);

    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key,可以做自己的业务
        String expiredKey = message.toString();

        if (expiredKey!=null && expiredKey.startsWith("OrderNo")){//从失效key中筛选代表订单失效的key
            //截取订单号，查询订单，如果是未支付状态则取消订单
            String orderNo=expiredKey.substring(7);
            //String 转为Long


            SysCollectionOrder sysCollectionOrder=new SysCollectionOrder();
            sysCollectionOrder.setCollectionOrderNo(orderNo);
            List<SysCollectionOrder> sysCollectionOrders = sysCollectionOrderService.selectSysCollectionOrderList(sysCollectionOrder);


            SysCollection sysCollection = new SysCollection();
            sysCollection.setIsSell("0");
            sysCollection.setCollectionId(sysCollectionOrders.get(0).getCollectionId());
            sysCollectionService.updateSysCollection(sysCollection);

            sysCollectionOrders.get(0).setOrderStatus("3");
            sysCollectionOrderService.updateSysCollectionOrder(sysCollectionOrders.get(0));
            System.out.println("订单号为："+orderNo+"的订单超时未支付，取消订单");

        }

    }
}
